﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using ConfExpert.Utility;
using ConfExpert.Utility.Ribbon;
using DevExpress.XtraEditors;
using Extensions;
using DevExpress.XtraGrid.Views.Grid.Customization;
using DevExpress.XtraTabbedMdi;

namespace Tailord
{
    public partial class MainForm : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        int WhoAmI = AppSession.UserInfo.UserId;
        System.Timers.Timer timer = null;
        DateTime alertTime1 = new DateTime(2000, 1, 1);
        Dictionary<string, XForm> forms = new Dictionary<string, XForm>();
        public Dictionary<int, double[]> PictureFeatures = new Dictionary<int, double[]>();

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            AppSession appSession = new AppSession("Tailord");
            ribbon.ForceInitialize();
            this.Text = "Tailord" + (AppSession.Version != null ? " - v" + AppSession.Version : "");


            bsiUser.Caption = ConfExpert.Utility.AppSession.UserInfo.UserName + " / " + ConfExpert.Utility.AppSession.DatabaseName;

            DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(ConfExpert.Forms.Login.SkinName);
            this.AllowFormGlass = DevExpress.Utils.DefaultBoolean.False;

            InitializeTimer();

            if (Properties.Settings.Default.BarcodeEnabled)
            {
                portBarcodeScanner = new System.IO.Ports.SerialPort(Properties.Settings.Default.BarcodeComPort);
                portBarcodeScanner.BaudRate = 57600;
                portBarcodeScanner.DataBits = 8;
                portBarcodeScanner.Parity = System.IO.Ports.Parity.Mark;
                portBarcodeScanner.StopBits = System.IO.Ports.StopBits.One;
                portBarcodeScanner.DtrEnable = true;
                try
                {

                    portBarcodeScanner.Open();
                    portBarcodeScanner.DataReceived += portBarcodeScanner_DataReceived;
                }
                catch (Exception ex)
                {

                }
            }
            
            this.KeyDown += new KeyEventHandler(MainForm_KeyDown);

            this.MdiChildActivate += new System.EventHandler(this.MainForm_MdiChildActivate);
            bbiRibbonSettings.ItemClick += bbiRibbonSettings_ItemClick;

            InitializeRibbon();
            this.WindowState = FormWindowState.Maximized;

            //SplashScreenManager.CloseForm();
        }

        void portBarcodeScanner_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            string formName = "NULL";

            string data = AppSession.MainForm.portBarcodeScanner.ReadExisting();
            biInfo.Caption = "1." + data + " (" + data.Length + ") / ";

            if (data.EndsWith("\r\n"))
            {
                data = data.Replace("\r\n", "");
                //ilk üç hane tip
                int type = data.Substring(0, 3).ToIntNN();//0;
                //son hane parity ve tip alanları atılınca geri kalan çıplak barkod
                int barcode = data.Substring(3, data.Length - 4).ToIntNN();//long.Parse( data);

                if (ActiveXForm != null && ActiveXForm.EnabledBarcodeTypes.Contains(type))
                {
                    ActiveXForm.FireBarcodeRead(type, barcode);
                    formName = ActiveXForm.GetType().ToString();
                }
                    

                biInfo.Caption += "2." + barcode.ToString() + " / ";
            }

            biInfo.Caption += "3." + ActiveXForm;
        }

        public XForm ActiveXForm = null;
        public System.IO.Ports.SerialPort portBarcodeScanner;

        public void SetActiveXFormFromMDIManager()
        {
            if (mdiManager.SelectedPage == null)
                ActiveXForm = null;
            else
            {
                XForm activeForm = mdiManager.SelectedPage.MdiChild as XForm;
                ActiveXForm = activeForm;
            }
        }

        private void mdiManager_SelectedPageChanged(object sender, EventArgs e)
        {
            SetActiveXFormFromMDIManager();

            if (mdiManager.SelectedPage != null)
            {
                XForm activeForm = mdiManager.SelectedPage.MdiChild as XForm;

                foreach (XtraMdiTabPage page in mdiManager.Pages)
                {
                    XForm form = page.MdiChild as XForm;
                    if (form != null && form != activeForm)
                    {
                        // form.BarcodeRead -= form.PO_BarcodeRead;
                        foreach (CustomizationForm cf in form.CustomizationForms)
                            cf.Hide();
                    }
                }

                if (activeForm != null)
                {
                    foreach (CustomizationForm cf in activeForm.CustomizationForms)
                        if (!cf.IsDisposed)
                            cf.Show();
                }
            }
        }

        private string GetHash(Type type, object[] prm)
        {
            string prmHash = "";
            foreach (object o in prm)
                prmHash += o.GetHashCode();

            return type.GetHashCode() + "." + prmHash;
        }

        public XForm GetActiveForm(Type type, params object[] prm)
        {
            XForm frm;
            string hash = GetHash(type, prm);

            forms.TryGetValue(hash, out frm);

            if (frm != null)
                if (!frm.IsDisposed)
                {
                    AppSession.DataManager.ExecuteNonQuery("InsLogForm", WhoAmI, frm.GetType().ToString());
                    frm.Activate();
                    return frm;
                }
                else
                    forms.Remove(hash);

            return null;
        }

        public XForm ShowMdiChildPopupAsNotModal(Type type, params object[] prm)
        {
            XForm frm = GetActiveForm(type, prm);

            if (frm != null)
            {
                ActiveXForm = frm;
                return frm;
            }

            try
            {
                if (type.BaseType == typeof(XPopupForm))
                {
                    using (XPopupForm popup = (XPopupForm)Activator.CreateInstance(type, prm))
                    {
                        AppSession.DataManager.ExecuteNonQuery("InsLogForm", WhoAmI, popup.GetType().ToString());
                        ActiveXForm = popup;
                        frm = popup;
                        popup.Show();
                    }
                }
                else
                {
                    frm = (XForm)Activator.CreateInstance(type, prm);
                    frm.MdiParent = this;
                    frm.WindowState = FormWindowState.Maximized;
                    string hash = GetHash(type, prm);
                    forms.Add(hash, frm);
                    AppSession.DataManager.ExecuteNonQuery("InsLogForm", WhoAmI, frm.GetType().ToString());
                    ActiveXForm = frm;
                    frm.Show();
                    frm.Activate();
                }
            }
            catch (Exception Ex)
            {
                XtraMessageBox.Show(Ex.InnerException.ToString());
            }

            // NotifyCustomSelectionInfo(frm);
            return frm;
        }

        void bbiRibbonSettings_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            using ( Options frm = new Options())
                frm.ShowDialog();
        }

        private void InitializeTimer()
        {
            timer = new System.Timers.Timer(60000);    //once a minute!
            timer.SynchronizingObject = this;
            timer.Elapsed += new System.Timers.ElapsedEventHandler(RaiseUpdate);
            timer.Enabled = true;
        }

        private void InitializeRibbon()
        {
            RibbonManager rm = new RibbonManager(Ribbon);
            rm.Init();
        }

       private void RaiseUpdate(object sender, System.Timers.ElapsedEventArgs e)
        {
            timer.Enabled = false;
            RefreshData();
            timer.Enabled = true;
        }
                
        private void MainForm_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.Control && e.KeyCode == Keys.F12)
            {
            }
        }

        private void MainForm_Shown(object sender, EventArgs e)
        {
            AppSession.MainForm.ShowInTaskbar = true;

            //AppSession.DataManager.ExecuteNonQuery("UpdLogPrg", AppSession.UserInfo.UserId, AppSession.Version, 0, 0, 0);
        }    

       
        
        private void MainForm_MdiChildActivate(object sender, EventArgs e)
        {
            XForm frm = (XForm)this.ActiveMdiChild;
            NotifySelectionInfo(frm);
        }

        public XForm ShowMdiChildForm(Type type, params object[] prm)
        {
            XForm frm = null;

            forms.TryGetValue(type.GetHashCode() + "." + prm.GetHashCode(), out frm);

            if (frm != null)
                if (!frm.IsDisposed)
                {
                    //AppSession.DataManager.ExecuteNonQuery("InsLogForm", WhoAmI, frm.GetType().ToString());
                    ActiveXForm = frm;
                    frm.Activate();
                    return frm;
                }
                else
                    forms.Remove(type.GetHashCode() + "." + prm.GetHashCode());

            try
            {
                if (type.BaseType == typeof(XPopupForm))
                {
                    using (XPopupForm popup = (XPopupForm)Activator.CreateInstance(type, prm))
                    {
                        //AppSession.DataManager.ExecuteNonQuery("InsLogForm", WhoAmI, popup.GetType().ToString());
                        ActiveXForm = popup;
                        popup.ShowDialog();
                    }
                }
                else
                {
                    frm = (XForm)Activator.CreateInstance(type, prm);
                    frm.MdiParent = this;
                    frm.WindowState = FormWindowState.Maximized;
                    forms.Add(type.GetHashCode() + "." + prm.GetHashCode(), frm);
                    //AppSession.DataManager.ExecuteNonQuery("InsLogForm", WhoAmI, frm.GetType().ToString());
                    ActiveXForm = frm;
                    frm.Show();
                }
            }
            catch (Exception Ex)
            {
                XtraMessageBox.Show(Ex.InnerException.ToString());
            }
            finally
            {

            }

            return frm;
        }

        public void NotifySelectionInfo(XForm frm)
        {
            if (frm != null && !frm.IsDisposed)
                bsiCustomSelectionInfo.Caption = frm.SelectionInfo;
        }
         
        public void RefreshData()
        {
            if (!bwRefreshLk.IsBusy)
                bwRefreshLk.RunWorkerAsync();
        }


        public void NotifyMain(string message)
        {
            bsiInfo.Caption = DateTime.Now.ToLongTimeString() + " | " + message;
        }
    }
}